#coding=utf-8
import logging, time
from google.appengine.ext import webapp
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db

from models import Stock, TradableShare, Code, create_stock, put_codes
from stockcrawler import get_stock, get_ts, get_codes
from utility import TimeMeth

def now():
    import time
    time_format = "%Y-%m-%d %H:%M:%S"
    return time.strftime(time_format)

class Init(webapp.RequestHandler):
    def get(self):
        taskqueue.add(url='/get_codes', method='GET')
        logging.info('Add Task Init on : %s'%now())
        
class CodeGetter(webapp.RequestHandler):
    def get(self):
        codes = get_codes('sh')
        put_codes(codes)
        taskqueue.add(url='/update_job', method='GET')
        
class Updater(webapp.RequestHandler):
    
    def get(self):
        
        cs = Code.all().fetch(50)
        if not cs:return
        
        codes = [c.code for c in cs]
    
        for code in codes:
            key_name='stock_%s'%code
            s = Stock.get_by_key_name(key_name)
            if not s:
                taskqueue.add(url='/new_stock', method='GET', params={'code': code})
            else:
                taskqueue.add(url='/update_ts', method='GET', params={'code': code})
                
        db.delete(cs)
        
        taskqueue.add(url='/update_job', method='GET')
           
class TsUpdater(webapp.RequestHandler):
    def get(self):
        
        code = self.request.get('code')
        s = Stock.gql("WHERE code = :1", code).fetch(1)[0]
        if s:
            data = get_ts(code)[code]
            s.update_tss(data)
          
class NewStock(webapp.RequestHandler):
    def get(self):
    
        code = self.request.get('code')
        
        key_name='stock_%s'%code
        s = Stock.get_by_key_name(key_name)
        
        if not s:
            s_data = get_stock(code)
            s = create_stock(s_data)
            taskqueue.add(url='/update_ts', method='GET', params={'code': code})
        
class Deleter(webapp.RequestHandler):
    def get(self):
        model = self.request.get('model')
        
        q = db.GqlQuery('select * from %s'%model)
        results = q.fetch(101)
        db.delete(results[:100])
        if len(results) == 101:
            taskqueue.add(url='/delete', method='GET', params={'model': model})
        
        

